import requests
from tools.log_util import INFO, ERROR


def phone_register_verify_code(phone_number: str,  app_biz_type, env: str):
    """发送验证码"""
    try:
        # 环境URLs
        env_urls = {
            "线上": 'https://api-bnd.yuntiancloud.com:18113/v1/servo/register',
            "测试": 'http://cg-sit-api-bnd.yuntiancloud.com/v1/servo/register',
            "UAT": 'http://cg-uat-api-bnd.yuntiancloud.com/v1/servo/register'
        }
        
        url = env_urls[env]
        
        data = {
            "app_userid": phone_number,
            "app_biz_type": app_biz_type, # 业务biz， 不同的业务biz，需要去申请
            "app_user_type": 999 # 999 是不走计费
        }
        response = requests.post(url=url, json=data, timeout=30)
        result = response.json()
        INFO.logger.info(result)
        return result, env
    except Exception as e:
        ERROR.logger.error(f"请求失败: {e}")
        return None, None


def format_result(result: dict, phone: str, env: str) -> None:
    """格式化并打印结果"""
    if not isinstance(result, dict):
        print("❌ 返回数据格式错误")
        return

    print("\n" + "="*50)
    print(f"📱 手机号: {phone}")
    print(f"🌐 当前环境: {env}")
    print("="*50)
    
    # 安全地获取ret字段的信息
    ret = result.get('ret', {})
    if isinstance(ret, dict):
        code = ret.get('code', '未知')
        msg = ret.get('msg', '未知')
        request_id = ret.get('request_id', '未知')
        
        print(f"📊 状态信息:")
        print(f"  ├─ 状态码: {code}")
        print(f"  ├─ 消息: {msg}")
        print(f"  └─ 请求ID: {request_id}")
    
    # 安全地获取user_info字段的信息
    user_info = result.get('user_info', {})
    if isinstance(user_info, dict):
        print(f"\n👤 用户信息:")
        print(f"  ├─ APP用户ID: {user_info.get('app_userid', '未知')}")
        print(f"  └─ 用户ID: {user_info.get('userid', '未知')}")
    print("="*50 + "\n")


if __name__ == '__main__':
    phone = '147258371'
    # 环境选择
    current_env = "线上"  # 可选: "线上", "测试", "UAT"
    result, env = phone_register_verify_code(phone, 57, current_env)
    if result:
        format_result(result, phone, env)
    else:
        print("❌ 请求失败，请检查日志获取详细错误信息")


